import React, { useState, useEffect, useRef } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import {
  Card,
  Tabs,
  Space,
  Button,
  Form,
  Row,
  Col,
  Input,
  message,
  Checkbox,
  notification,
  Modal,
  Table,
  InputNumber,
} from 'antd';
import { connect, useIntl } from 'umi';
import { PlusOutlined, CloseOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import DMRActn from './components/dmrActn';
import request from '@/utils/request';
import moment from 'moment';
import QuickMenu from '@/components/QuickMenu';
import OperpQuery from '@/components/OperpQuery';

const { TabPane } = Tabs;
const { confirm } = Modal;
const apiURL = '/api/services/app/DMRHead/';
const apiURL2 = '/api/services/app/DMRActn/';

const ViewPage: React.FC<any> = (props) => {
  const [loading, setLoading] = useState(false);
  const [visible, setVisible] = useState(false);
  const [data, setData] = useState<any>({
    data: { dmrNum: '0', id: '0' },
    details: [],
  });
  const [defTab, setDefTab] = useState('1');
  const [freshNum, setFreshNum] = useState(1);
  const [selectedRowKeys, setSelectedRowKeys] = useState<any[]>([]);
  const [record, setRecord] = useState(null);
  const formRef = useRef<any>(null);
  const inspDtl = useRef<any>(null);
  const intl = useIntl();

  useEffect(() => {
    formRef.current.setFieldsValue({ DMRHead: data });
  }, []);

  const onFinish = (values: any) => {
    if (defTab === '1') {
      save(values.DMRHead);
    } else {
      inspDtl.current.formRef.current.submit();
    }
  };

  const resetForm = () => {
    const data = {
      data: { dmrNum: '0', id: '0' },
      details: [],
    };
    formRef.current.resetFields();
    formRef.current.setFieldsValue({ DMRHead: data.data });
    setData(data);
  };

  const save = (model: any) => {
    let act = 'Modify';
    const method = 'POST';
    if (model.id === '0') {
      act = 'New';
    }
    request(apiURL + act, {
      method,
      data: model,
    }).then((response) => {
      if (response) {
        if (response.success) {
          message.success(intl.formatMessage({ id: 'pages.save.success' }));
          getObj(model.inspNum);
        }
        setLoading(false);
      }
    });
  };

  const tabSwitch = (key: any) => {
    setDefTab(key);
  };

  const getObj = (value: any) => {
    if (!value) {
      return;
    }
    setLoading(true);
    request(apiURL + 'GetByNum', {
      method: 'GET',
      params: { num: value },
    }).then((response) => {
      if (response) {
        if (response.success) {
          const result = response.result;
          const DMRHead = response.result.data;
          if (DMRHead) {
            if (DMRHead.inspDate) DMRHead.inspDate = moment(DMRHead.inspDate);
            formRef.current.setFieldsValue({ DMRHead });
            setData(result);
            setVisible(false);
            setLoading(false);
            setFreshNum(freshNum + 1);
          }
        } else {
          notification.error({
            message: response.error.message,
            description: response.error.details,
          });
        }
        setLoading(false);
        setFreshNum(freshNum + 1);
      }
    });
  };

  const delObj = () => {
    if (data.data) {
      confirm({
        title: intl.formatMessage({ id: 'pages.warning' }),
        icon: <ExclamationCircleOutlined />,
        content: intl.formatMessage({ id: 'pages.delete.confirm' }),
        onOk() {
          request(apiURL + 'DelBatch', {
            method: 'POST',
            params: [data.data.id],
          }).then((response) => {
            if (response) {
              if (response.success) {
                setFreshNum(freshNum + 1);
                resetForm();
              }
            }
          });
        },
      });
    }
  };

  const switchModal = (visible: boolean, record: any = null) => {
    if (record == null) {
      record = {
        dmrNum: data.data.dmrNum,
        partNum: data.data.partNum,
        partDescription: data.data.partDescription,
        quantity: data.data.quantity,
        ium: data.data.ium,
        lotNum: data.data.lotNum,
      };
    } else {
      record.partNum = data.data.partNum;
      record.partDescription = data.data.partDescription;
      record.ium = data.data.ium;
    }
    setVisible(visible);
    setRecord(record);
  };

  const delDtl = () => {
    confirm({
      title: intl.formatMessage({ id: 'pages.warning' }),
      icon: <ExclamationCircleOutlined />,
      content: intl.formatMessage({ id: 'pages.delete.confirm' }),
      onOk() {
        request(apiURL2 + 'DelBatch', {
          method: 'POST',
          params: [data.data.id],
        }).then((response) => {
          if (response) {
            if (response.success) {
              const _data = data;
              _data.details = data.details.filter((o: any) => selectedRowKeys.indexOf(o.id) < 0);
              setData(_data);
              setFreshNum(freshNum + 1);
            }
          }
        });
      },
    });
  };

  const layout = {
    labelCol: { span: 5 },
    wrapperCol: { span: 19 },
  };

  const columns = [
    {
      title: intl.formatMessage({ id: 'pages.dmrNum' }),
      dataIndex: 'dmrNum',
    },
    {
      title: intl.formatMessage({ id: 'pages.actionDate' }),
      dataIndex: 'actionDate',
      render: (text: string) => <span>{moment(text).format('YYYY-MM-DD')}</span>,
    },
    {
      title: intl.formatMessage({ id: 'pages.warehouseCode' }),
      dataIndex: 'warehouseCode',
    },
    {
      title: intl.formatMessage({ id: 'pages.binNum' }),
      dataIndex: 'binNum',
    },
    {
      title: intl.formatMessage({ id: 'pages.quantity' }),
      dataIndex: 'quantity',
    },
    {
      title: intl.formatMessage({ id: 'pages.IUM' }),
      dataIndex: 'ium',
    },
    {
      title: intl.formatMessage({ id: 'pages.actionType' }),
      dataIndex: 'actionType',
    },
    {
      title: intl.formatMessage({ id: 'pages.reasonCode' }),
      dataIndex: 'reasonCode',
    },
    {
      title: intl.formatMessage({ id: 'pages.openline' }),
      dataIndex: 'openDMR',
      key: 'openDMR',
      render: (text: boolean) => <Checkbox checked={text} />,
    },
  ];

  const rowSelection = {
    selectedRowKeys,
    onChange: (_keys: any) => {
      setSelectedRowKeys(_keys);
    },
  };

  return (
    <PageHeaderWrapper title={false} breadcrumbRender={false} ghost>
      <Form {...layout} ref={formRef} onFinish={onFinish}>
        <Card
          title={intl.formatMessage({ id: 'menu.Inspect.dmrEntry' })}
          extra={
            <Space>
              <Button key="1" type="primary" icon={<PlusOutlined />} onClick={resetForm}>
                {intl.formatMessage({ id: 'pages.new' })}
              </Button>
              <Button key="2" type="primary" htmlType="submit">
                {intl.formatMessage({ id: 'pages.save' })}
              </Button>
              <Button
                key="4"
                type="dashed"
                danger
                icon={<CloseOutlined />}
                onClick={delObj}
                disabled={data.data.id === '0'}
              >
                {intl.formatMessage({ id: 'pages.delete' })}
              </Button>
              <QuickMenu path="/Inspect/dmrEntry" icon="icon-document" title="pages.DMR" />
            </Space>
          }
        >
          <Tabs defaultActiveKey={defTab} activeKey={defTab} onChange={tabSwitch}>
            <TabPane tab={intl.formatMessage({ id: 'pages.summary' })} key="1">
              <Row>
                <Col span={12}>
                  <Form.Item name={['DMRHead', 'id']} hidden={true}>
                    <Input />
                  </Form.Item>
                  <Form.Item
                    name={['DMRHead', 'dmrNum']}
                    label={intl.formatMessage({ id: 'pages.dmrNum' })}
                    rules={[{ required: true, message: intl.formatMessage({ id: 'pages.dmrNum.required' }) }]}
                  >
                    <Input
                      style={{ width: 200 }}
                      onBlur={(e: any) => getObj(e.target.value)}
                      disabled
                    />
                  </Form.Item>
                  <Form.Item label={intl.formatMessage({ id: 'pages.partNum' })} style={{ marginBottom: 0 }}>
                    <Input.Group compact>
                      <Form.Item
                        name={['DMRHead', 'partNum']}
                        rules={[{ required: true, message: intl.formatMessage({ id: 'pages.partNum.required' }) }]}
                      >
                        <Input disabled style={{ width: 130 }} />
                      </Form.Item>
                      <Form.Item
                        name={['DMRHead', 'ium']}
                        rules={[{ required: true, message: intl.formatMessage({ id: 'pages.IUM.required' }) }]}
                      >
                        <Input disabled placeholder={intl.formatMessage({ id: 'pages.IUM' })} style={{ width: 70 }} />
                      </Form.Item>
                      <Form.Item name={['DMRHead', 'revisionNum']}>
                        <Input disabled placeholder={intl.formatMessage({ id: 'pages.revision' })} style={{ width: 70 }} />
                      </Form.Item>
                    </Input.Group>
                  </Form.Item>
                  <Form.Item
                    name={['DMRHead', 'partDescription']}
                    label={intl.formatMessage({ id: 'pages.partDescription' })}
                    rules={[{ required: true, message: intl.formatMessage({ id: 'pages.partDescription.required' }) }]}
                  >
                    <Input disabled />
                  </Form.Item>
                  <Form.Item label={intl.formatMessage({ id: 'pages.jobNum' })} style={{ marginBottom: 0 }}>
                    <Input.Group compact>
                      <Form.Item name={['DMRHead', 'jobNum']}>
                        <Input disabled style={{ width: 120 }} placeholder={intl.formatMessage({ id: 'pages.jobNum' })} />
                      </Form.Item>
                      <Form.Item name={['DMRHead', 'assemblySeq']}>
                        <Input disabled placeholder={intl.formatMessage({ id: 'pages.assemblySeq' })} style={{ width: 80 }} />
                      </Form.Item>
                      <Form.Item name={['DMRHead', 'mtlSeq']}>
                        <Input disabled placeholder={intl.formatMessage({ id: 'pages.mtlSeq' })} style={{ width: 80 }} />
                      </Form.Item>
                      <Form.Item name={['DMRHead', 'jobSeq']}>
                        <Input disabled placeholder={intl.formatMessage({ id: 'pages.jobSeq' })} style={{ width: 80 }} />
                      </Form.Item>
                    </Input.Group>
                  </Form.Item>
                  <Form.Item label={intl.formatMessage({ id: 'pages.poNum' })} style={{ marginBottom: 0 }}>
                    <Input.Group compact>
                      <Form.Item name={['DMRHead', 'poNum']}>
                        <Input disabled style={{ width: 120 }} placeholder={intl.formatMessage({ id: 'pages.poNum' })} />
                      </Form.Item>
                      <Form.Item name={['DMRHead', 'poLine']}>
                        <Input disabled style={{ width: 80 }} placeholder={intl.formatMessage({ id: 'pages.poLine' })} />
                      </Form.Item>
                      <Form.Item name={['DMRHead', 'poRelNum']}>
                        <Input disabled style={{ width: 80 }} placeholder={intl.formatMessage({ id: 'pages.poRelNum' })} />
                      </Form.Item>
                    </Input.Group>
                  </Form.Item>
                </Col>
                <Col span={12}>
                  <Form.Item name={['DMRHead', 'commentText']} label={intl.formatMessage({ id: 'pages.commentText' })}>
                    <Input.TextArea />
                  </Form.Item>
                  <Form.Item label={intl.formatMessage({ id: 'pages.quantity' })}>
                    <Form.Item name={['DMRHead', 'quantity']}>
                      <InputNumber min={0} />
                    </Form.Item>
                    <Input.Group compact>
                      <Form.Item name={['DMRHead', 'openDMR']} valuePropName="checked">
                        <Checkbox disabled>{intl.formatMessage({ id: 'pages.openline' })}</Checkbox>
                      </Form.Item>
                    </Input.Group>
                  </Form.Item>
                </Col>
              </Row>
            </TabPane>
            <TabPane tab={intl.formatMessage({ id: 'pages.details' })} key="2">
              <Table
                rowKey="id"
                size="small"
                columns={columns}
                loading={loading}
                dataSource={data.details}
                rowSelection={rowSelection}
                onRow={(_record) => {
                  return {
                    onDoubleClick: () => {
                      switchModal(true, _record);
                    },
                  };
                }}
                footer={() => (
                  <Space>
                    <Button
                      type="dashed"
                      icon={<PlusOutlined />}
                      onClick={() => switchModal(true)}
                    >
                      {intl.formatMessage({ id: 'pages.newDetail' })}
                    </Button>
                    <Button
                      type="dashed"
                      danger
                      icon={<CloseOutlined />}
                      onClick={delDtl}
                      disabled={selectedRowKeys.length <= 0}
                    >
                      {intl.formatMessage({ id: 'pages.deleteSelected' })}
                    </Button>
                  </Space>
                )}
              />
            </TabPane>
          </Tabs>
        </Card>
      </Form>
      <OperpQuery
        sysReportName="ReportDMR"
        scroll={{ x: 'max-content', y: '200px' }}
        freshNum={freshNum}
        callback={(e) => getObj(e.DMRNum)}
      />
      <Modal
        title={intl.formatMessage({ id: 'pages.DMR.detail' })}
        visible={visible}
        destroyOnClose={true}
        onCancel={() => switchModal(false)}
        footer={false}
      >
        <DMRActn onRef={(ref: any) => (inspDtl.current = ref)} data={record} refreshData={getObj} />
      </Modal>
    </PageHeaderWrapper>
  );
};

export default connect(({ Abp }: API.IConnectState) => ({
  response: Abp.response,
  currentUser: Abp.currentUser,
}))(ViewPage);
